<?php

declare(strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use app\common\model\Level;
use app\common\model\UserRole;
use app\common\model\User;
use app\common\model\Logs;
use app\common\tool\Result;
use think\facade\View;
use think\Response;
use think\exception\ValidateException;
use think\response\Json;
use think\facade\Cache;
//该文件为自动生成，请按需修改
class Expert extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\Expert';

    protected array $hasOne = ['user'];
    protected string $validate = 'Expert';

    protected $append = ['status_text'];
    /**
     * 健康管理师
     */
    public function manager(): string
    {
        Cache::set('expert_type', 2);
        return Builder::Table()
            ->autoStructure($this->model, $this->pk, 'expertDemo,200')
            ->addRightButtons(['edit' => ['size' => '60%'], 'delete'])
            ->addTopButtons(['add' => ['size' => '60%']])
            ->addExtraMap([['type', '=', 2]])
            ->addExtraHtml(['expert'])
            ->fetch();
    }
    /**
     * 专家团队
     */
    public function expert(): string
    {
        Cache::set('expert_type', 3);
        return $this->index(3, 'getJobExpert');
    }
    /**
     * 团队服务
     */
    public function team(): string
    {
        Cache::set('expert_type', 4);
        return $this->index(4, 'getJobTeam');
    }


    public function index($type, $job): string
    {
        return Builder::Table()
            ->addColumn(['type' => 'checkbox', 'title' => '全选', 'fixed' => 'left'])
            ->addColumn(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addColumn(['field' => 'uid', 'title' => '相关会员', 'modify' => '3,selectSearch', 'width' => 250, 'templet' => '#_userTpl'])
            ->addColumn(['field' => 'rname', 'title' => '姓名', 'modify' => '2,input'])
            ->addColumn(['field' => 'icon', 'title' => '头像', 'modify' => '2,img,1', 'templet' => '#iconTpl'])
            ->addColumn(['field' => 'job', 'title' => '职称', 'modify' => '2,input,'])
            ->addColumn(['field' => 'speciality', 'title' => '擅长', 'modify' => '2,textarea'])
            ->addColumn(['field' => 'note', 'title' => '简介', 'modify' => '2,textarea'])
            ->addColumn(['field' => 'images', 'title' => '资质证书', 'modify' => '2,img,10', 'templet' => '#imagesTpl'])
            ->addColumn(['field' => 'create_time', 'title' => '提交时间'])
            ->addColumn(['field' => 'update_time', 'title' => '修改时间'])
            ->addColumn(['field' => 'status_text', 'title' => '状态'])
            ->addColumn(['field' => 'confirm_time', 'title' => '审核时间'])
            ->addColumn(['field' => 'admin_name', 'title' => '审核人'])
            ->addColumn(['field' => 'reject_msg', 'title' => '驳回原因'])
            ->addColumn(['fixed' => 'right', 'title' => '操作', 'align' => 'center', 'toolbar' => '#expertDemo', 'width' => 200])
            ->addRightButtons([
                'edit' => ['size' => '60%'],
                'delete',
                'audit' => [
                    'title'       => '审核',
                    'unity_title' => '审核详情',
                    'url'   => url('expert/audit')->build()
                ]
            ])
            ->addExtraMap([['type', '=', $type]])
            ->addExtraHtml(['expert'])
            ->fetch();
    }
    public function save($param = [], $model = false): Json
    {
        $param = $this->request->post();
        $type = Cache::get('expert_type');
        if ($type == 2) {
            $data['level_id'] = $type;
            $param['status'] = 2;
        }
        $data['job'] = $param['job'] ?? '';
        User::where('id', $param['uid'])->update($data);
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }
    /**
     * 服务团队
     */
    public static function getJob()
    {
        $Role = UserRole::where('type', 2)->select();
        $list = [];
        foreach ($Role as $k => $v) {
            $list[$v['id']] = $v['title'];
        }
        return $list;
    }
    public static function getJobExpert()
    {
        $Role = UserRole::where('type', 3)->select();
        $list = [];
        $list[0] = '暂无';
        foreach ($Role as $k => $v) {
            $list[$v['id']] = $v['title'];
        }
        return $list;
    }
    public static function getJobTeam()
    {
        $Role = UserRole::where('type', 4)->select();
        $list = [];
        $list[0] = '暂无';
        foreach ($Role as $k => $v) {
            $list[$v['id']] = $v['title'];
        }
        return $list;
    }
    /**
     * 获取相关会员列表
     */
    public  function getUserList()
    {
        try {
            $param = $this->request->param();
            $user = User::where('level_id', 1)->whereLike('code|mobile|nickname', '%' . $param['val'] . '%')
                ->field('id,code,mobile,nickname')->select();
            return Result::success('success', $user, 0);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取用户信息
     */
    public  function getUserInfo()
    {
        try {
            $param = $this->request->param();
            $user = User::where('id', $param['uid'])->field('id,code,mobile,nickname')->find();
            return Result::success('success', $user, 0);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 审核信息
     */
    public function audit($id = '')
    {

        if ($this->request->isPost()) {
            $param = $this->request->param();
            try {
                return Result::fastReturn($this->model::audit($param, $this->admin));
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }
        }
        $info = $this->model::find($id);
        View::assign([
            'info'    => $info,
            'job' => \app\common\model\UserRole::where(['type' => $info->type])->select()
        ]);
        return View::fetch();
    }
    public function delete(): Response
    {
        try {
            $info = $this->model::where('id', $this->request->post($this->pk))->find();
            if (empty($info)) {
                return Result::fail('申请信息不存在');
            }
            $level_title = Level::where(['id' => $info['type']])->value('title');
            User::where(['id' => $info['uid']])->update(['level_id' => 1, 'role_id' => 0]);
            $this->model::destroy(['id' => $info->id], true);
            Logs::adds('删除' . $level_title . '【' . $info->rname . '】', $this->admin->id, $this->admin->admin_name);
            return Result::success('已删除');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
